package com.az.usr.service.impl;


import cn.hutool.core.bean.BeanUtil;
import com.az.miaoapi.exception.BaseException;
import com.az.miaoapi.response.ResponseCode;
import com.az.usr.domain.dto.UserMessageDto;
import com.az.usr.domain.po.UserMessage;
import com.az.miaoapi.vo.Null;
import com.az.miaoapi.vo.TheVo;
import com.az.usr.domain.vo.UserMessageVo;
import com.az.usr.mapper.UserMessageMapper;
import com.az.usr.service.UserMessageService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.Cache;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.context.annotation.Lazy;
import org.springframework.retry.annotation.Retryable;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author baomidou
 * @since 2024-09-17
 */
@Service
@Slf4j
public class UserMessageServiceImpl extends ServiceImpl<UserMessageMapper, UserMessage> implements UserMessageService {

    @Autowired
    @Lazy //避免循环依赖
    private UserMessageService userMessageService;

    @Autowired
    private CacheManager cacheManager;

    @Cacheable(value = "userMessages", key = "#userId")
    @Retryable(noRetryFor = BaseException.class)
    public UserMessageVo getMessage(long userId) {
        // 1.查询数据库
        QueryWrapper<UserMessage> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId);
        UserMessage userMessage = userMessageService.getOne(queryWrapper);
        // 1.1数据库中不存在
        if (userMessage == null) {
            throw new BaseException(ResponseCode.NOT_FOUND_USERMESSAGE);
        }
        LocalDateTime birthday = userMessage.getBirthday();
//        log.info(userMessage.toString());
        UserMessageVo userMessageVo = BeanUtil.copyProperties(userMessage, UserMessageVo.class);
        // 2.格式化生日
        if (birthday != null) {
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
            String formattedBirthday = dateFormat.format(birthday);
            userMessageVo.setBirthdays(formattedBirthday);
        }
        return userMessageVo;
    }

    @Override
    @Retryable(noRetryFor = BaseException.class)
    public TheVo updateUserMessage(UserMessageDto userMessageDto, long userId)  {
//        1.判断数据库是否存在
        QueryWrapper<UserMessage> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId);
        UserMessage userMessage = userMessageService.getOne(queryWrapper);
//        1.1不存在
        if (userMessage == null) {
            userMessage = new UserMessage();
            userMessage.setUserId(userId);
        }
        UserMessage updateMessage = ToUserMessage(userMessageDto);
        boolean update = userMessageService.saveOrUpdate(updateMessage);
        if (!update) throw new BaseException(ResponseCode.UPDATE_USERMESSAGE_FAILED);
        // 清除缓存
        Cache cache = cacheManager.getCache("userMessages");
        if (cache != null) {
            cache.evictIfPresent(userId);
        }
        return new Null();
    }
    private UserMessage ToUserMessage(UserMessageDto userMessageDto){
        String image = userMessageDto.getImage();
        Integer gender=userMessageDto.getGender();
        String birthday = userMessageDto.getBirthday();
        String Phone_number = userMessageDto.getPhone_number();
        String email = userMessageDto.getEmail();//弃用
        String nickname = userMessageDto.getNickname();
        String sex = gender == 1 ? "男" : "女";
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        LocalDate localDate = LocalDate.parse(birthday, formatter);
        LocalDateTime localDateTime = localDate.atStartOfDay();
        UserMessage userMessage =new UserMessage();
        userMessage.setSex(sex);
        userMessage.setAvatar(image);
        userMessage.setNickname(nickname);
        userMessage.setBirthday(localDateTime);
        userMessage.setPhoneNumber(Phone_number);
        return userMessage;
    }

}
